package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

//跨域中间件
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin","http://localhost:8080") //允许8080端口访问。也可以写 * ，代表所有域名都可以访问
		c.Writer.Header().Set("Access-Control-Max-Age","86400") //缓存时间
		c.Writer.Header().Set("Access-Control-Allow-Methods","*") //请求方法
		c.Writer.Header().Set("Access-Control-Allow-Headers","*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials","true")

		if c.Request.Method == http.MethodOptions{  //判断请求方法是否为Option请求
			c.AbortWithStatus(200)
		}else{
			c.Next()
		}

	}
}